package com.css.fxfzdzzh.modules.reportManagement.service;

import cn.hutool.core.io.FileUtil;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.modules.reportManagement.entity.BreakReport;
import com.css.fxfzdzzh.modules.reportManagement.entity.MultipleReport;
import com.css.fxfzdzzh.modules.reportManagement.entity.Report;
import com.css.fxfzdzzh.modules.reportManagement.entity.ReportCheckRecode;
import com.css.fxfzdzzh.modules.reportManagement.param.ReportCheckQueryParam;
import com.css.fxfzdzzh.modules.reportManagement.repository.MultipleReportRepository;
import com.css.fxfzdzzh.modules.reportManagement.repository.ReportCheckRepository;
import com.css.fxfzdzzh.modules.reportManagement.repository.ReportRepository;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.util.FileUploadUtil;
import com.css.fxfzdzzh.util.ResponseCreator;
import com.css.fxfzdzzh.util.UUIDGenerator;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.ServiceMode;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Dbj
 * @date 2023年05月12日  11:07
 */
@Service
public class ReportCheckService {

    @Resource
    ReportCheckRepository reportCheckRepository;
    @Resource
    ReportRepository reportRepository;
    @Resource
    MultipleReportRepository multipleReportRepository;
    @Value("${file.localDir}")
    private String localDir;
    @Resource
    SUserService sUserService;

    public Map<String, Object> page(ReportCheckQueryParam param, int curPage, int pageSize) {
        return reportCheckRepository.page(param,curPage,pageSize);
    }

    public void downloadFile(String localReport, String reportSavePath, HttpServletResponse res) {
        FileUploadUtil.download(reportSavePath + File.separator + localReport, res);

    }

    @Transactional(rollbackFor = Exception.class)
    public void audit(Report report) {
        String reportType = report.getReportType();
        String userId =PlatformSessionContext.getUserID();
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        ReportCheckRecode reportCheckRecode = new ReportCheckRecode();
        if("1".equals(reportType)){
             //地表破裂带评估报告
            reportRepository.reportAudit(report,sUser);
            BreakReport breakReport = reportRepository.getReportById(report.getReportId());
            reportCheckRecode.setNum(breakReport.getNum());
            reportCheckRecode.setName(breakReport.getUploadBreakReportName());
            reportCheckRecode.setSubmitUserId(breakReport.getSubmitUserId());
            reportCheckRecode.setSubmitUserName(breakReport.getSubmitUserName());
            reportCheckRecode.setDistrict(breakReport.getDistrict());
            reportCheckRecode.setReportName(breakReport.getUploadBreakReportName());
            reportCheckRecode.setLocalReportName(breakReport.getDiskUploadBreakReportName());
        }else if("2".equals(reportType)){
            //滑坡/砂土液化/软土震陷评估报告
            multipleReportRepository.reportAudit(report,sUser);
            MultipleReport multipleReport = multipleReportRepository.getReportById(report.getReportId());
            reportCheckRecode.setNum(multipleReport.getNum());
            reportCheckRecode.setName(multipleReport.getTaskName());
            reportCheckRecode.setSubmitUserId(multipleReport.getSubmitUserId());
            reportCheckRecode.setSubmitUserName(multipleReport.getSubmitUserName());
            reportCheckRecode.setDistrict(multipleReport.getDistrict());
            reportCheckRecode.setReportName(multipleReport.getUploadMultipleReportName());
            reportCheckRecode.setLocalReportName(multipleReport.getDiskUploadMultipleReportName());
        }
        reportCheckRecode.setRejectFile(report.getRejectFile());
        reportCheckRecode.setRejectRealFile(report.getRejectRealFile());
        reportCheckRecode.setRejectAdvice(report.getRejectAdvice());
        reportCheckRecode.setSavePath(localDir);
        reportCheckRecode.setCheckStatus(report.getCheckStatus());
        reportCheckRecode.setCheckUserId(userId);
        reportCheckRecode.setCheckTime(new Date());
        reportCheckRecode.setDrcrId(UUIDGenerator.getUUID());
        reportCheckRepository.saveCheckRecord(reportCheckRecode);
    }

    public RestResponse uploadAttachment(MultipartFile file, String reportId,String reportType) throws IOException {
        Map<String,Object> map = new HashMap<>();
        if (file == null) {
            return ResponseCreator.createFailResponse("上传失败，请选择文件");
        }
        //获取文件名称
        String fileName = file.getOriginalFilename();
        map.put("fileName",fileName);
        //获取文件上传的本地路径
        String savePath = localDir;
        //上传文件
        String prefix = FileUtil.getPrefix(fileName);
        prefix+=System.currentTimeMillis();
        String suffix = FileUtil.getSuffix(fileName);
        String realFileName = prefix+"."+suffix;
        uploadFile(realFileName, savePath, file);
        map.put("realFileName",realFileName);
        if("1".equals(reportType)){
             //地表破裂带评估不通过附件
            reportRepository.uploadAttachment(fileName,realFileName,reportId);
        }else if("2".equals(reportType)){
            //滑坡/砂土液化/软土震陷不通过附件
            multipleReportRepository.uploadAttachment(fileName,realFileName,reportId);
        }
        map.put("savePath",localDir);
        return ResponseCreator.createSuccessResponse(map);
    }

    private void uploadFile(String fileName, String savePath, MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        //判断文件夹是否存在如果不存在则创建
        if (!new File(savePath).exists()) {
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, fileName);
        multipartFile.transferTo(file);
    }

    public Map<String, Object> recordPage(ReportCheckQueryParam param, int curPage, int pageSize) {
        return reportCheckRepository.recordPage(param,curPage,pageSize);
    }

    public void downLoadReFile(Map<String, Object> map, HttpServletResponse res) {
        FileUploadUtil.download(map.get("savePath") + File.separator + map.get("realFileName"), res);
    }

    public void cancelAudit(Map<String, String> map) {
        reportCheckRepository.cancelAudit(map.get("reportId"),map.get("reportType"));
    }
}
